<!--
 * @Author: your name
 * @Date: 2021-03-11 11:06:18
 * @LastEditTime: 2021-05-06 20:47:39
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \jet_mesc:\js\jinma_qms\src\components\ToggleSelect.vue
-->
<template>
  <q-select
    filled
    use-input
    v-model="serialization"
    :options="options"
    :label="field.label"
    lazy-rules
    :rules="field.rules ? field.rules : null"
    @filter="filterFn"
    :readonly="readonly"
    :dense="dense"
    :display-value="displayValue"
    ref="select"
    multiple
    emit-value
    map-options
    bottom-slots
  >
    <template v-slot:no-option>
      <q-item>
        <q-item-section class="text-grey">
          无选择结果
        </q-item-section>
      </q-item>
    </template>
    <template v-slot:hint v-if="field.hint || field.compare">
      <div class="text-bold text-white bg-yellow-10" style="padding: 1px;" v-if="canShowCompare">
        {{field.compare.label ? field.compare.label + '：' : ''}}{{field.compare.map ? field.compare.map.value : field.compare.value}}
      </div>
      <div v-if="field.hint">{{field.hint}}</div>
    </template>
    <template v-slot:option="{ itemProps, itemEvents, opt, selected, toggleOption }">
      <q-item
        v-bind="itemProps"
        v-on="itemEvents"
      >
        <q-item-section class="text-grey-8">
          <q-item-label v-html="displayLabel(opt, selected)" ></q-item-label>
        </q-item-section>
        <q-item-section>
          <q-toggle :value="selected" @input="toggleOption(opt)" />
        </q-item-section>
      </q-item>
    </template>
  </q-select>
</template>

<script>
import { defineComponent } from 'vue';
import pinyin from 'src/lib/vue-py';
import { useStore } from 'stores/store';

export default defineComponent({
  name: 'toggleSelect',
  props: {
    field: {
      type: Object,
      default: () => []
    }
  },
  data () {
    const $store = useStore();
    if (!this.field.options) this.field.options = [];
    if (this.field.dict && $store.dictionary[this.field.dict] && this.field.options.length == 0) {
      this.field.options = JSON.parse(JSON.stringify($store.dictionary[this.field.dict]));
    }
    return {
      options: this.field.options,
      $store
    }
  },
  methods: {
    filterFn (val, update, abort) {
      const $store = useStore();
      if (typeof this.field.filterFn === 'function') {
        this.field.filterFn(val, abort, opts => {
          update(() => {
            this.options = opts;
          });
        });
      } else {
        if (!this.field.options) this.field.options = [];
        if (this.field.dict && $store.dictionary[this.field.dict] && this.field.options.length == 0) {
          this.field.options = JSON.parse(JSON.stringify($store.dictionary[this.field.dict]));
        }
        update(() => {
          this.options = this.field.options.filter(v => {
            const py = pinyin.chineseToPinYin(v.label || '', true).toLowerCase() || '';
            return v.label && (v.label.indexOf(val) > -1 || py.indexOf(val.toLowerCase()) > -1)
          })
        })
      }
    },
    sendOption (val) {
      // 把选中option发送出去
      if (!val) { // 空值
        this.field.selected = null;
      } else {
        const self = this;
        const valArr = String(val).split(',');
        const optArr = [];
        valArr.forEach(item => {
          optArr.push(self.options.filter(v => v.value == item)[0]);
        });
        this.field.selected = optArr;
      }
    },
    displayLabel (opt, selected) {
      const valArr = this.field.value ? this.field.value.split(',') : [];
      const { value, label } = opt;
      // console.log(valArr, opt);
      const idx = valArr.indexOf(String(value));
      return idx < 0 ? label : `<span class="text-green-9 text-bold">${idx + 1}</span> ${label}`;
    }
  },
  computed: {
    serialization: {
      get () {
        const val = this.field.value || null;// 多选时，若为''，会出错，要设为null
        this.sendOption(val);
        return val && this.field.value.split(',').map(v => !isNaN(v) ? parseInt(v) : v); // 多选时为数组
      },
      set (val) {
        val = Object.prototype.toString.call(val) === '[object Array]' && val.length === 0 ? null : val; // 返回为空数组时置为null
        this.field.value = val && val.join(',');
      }
    },
    readonly () {
      return !!this.field.readonly;
    },
    dense () {
      return !!this.field.dense;
    },
    displayValue () {
      const self = this;
      const valArr = this.field.value ? this.field.value.split(',') : [];
      let display = '';
      if (this.field.options.length > 0) {
        display = valArr.length > 0 ? valArr.map((val, idx) => `${self.field.options.filter(v => v.value == val)[0].label}`).join('<i aria-hidden="true" role="presentation" class="material-icons q-icon notranslate text-green-9 text-bold">arrow_forward</i>') : '';
      }
      return display;
    },
    canShowCompare () {
      /*
        compare的值
        compare: {
          label, // 标题
          value, // 对比的值
          always // true-有数据就显示 false-值不同，再显示
        } */
      return this.field.compare && this.field.compare.value !== null && (this.field.compare.always || this.field.compare.value != this.field.value);
    }
  },
  watch: {
    '$store.dictionary' (val) { // 字典有数据后，加载到options
      if (this.field.dict && val[this.field.dict] && this.options.length < 1) {
        this.field.options = JSON.parse(JSON.stringify(this.$store.dictionary[this.field.dict]));
        this.options = this.field.options;
      }
    }
  }
});
</script>
